package work.thread_eg.concurrent.lock;

import java.util.concurrent.Exchanger;

/**
 * Exchanger交换器
 *
 * 用法
 * 1） 线程之间通信 交互变量 只能两个线程进行交换
 *
 */
public class ExchangerTest01 {

    static Exchanger<String> exchanger = new Exchanger<>();

    public static void main(String[] args) {
        new Thread(()-> {
            String s = "T1";
            try {
                // exchange() 阻塞方法
                // 把变量放到exchanger容器中 进行交换
                s  = exchanger.exchange(s);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+ "  " +s);
        },"t1").start();

        new Thread(()-> {
            String s = "T2";
            try {
                s  = exchanger.exchange(s);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+ "  " +s);
        },"t2").start();


    }
}
